package leetcode_day._2022._202203._0110;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @author yzh
 * @version 1.0
 * @date 2022/3/10 19:38
 * N 叉树的前序遍历
 * 算法：递归、迭代
 */
public class _10_589 {
    public List<Integer> preorder(Node root) {
        List<Integer> ans = new ArrayList<>();
        dfs(root, ans);
        return ans;
    }
    private void dfs(Node node, List<Integer> ans) {
        if (node == null) return;
        ans.add(node.val);
        for (Node n : node.children) dfs(n, ans);
    }

    public List<Integer> preorder_iteration(Node root) {
        List<Integer> ans = new ArrayList<>();
        if (root == null) return ans;
        Deque<Node> stack = new LinkedList<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node pop = stack.pop();
            ans.add(pop.val);
            for (int i = pop.children.size() - 1; i >= 0; i--) stack.push(pop.children.get(i));
        }
        return ans;
    }

}
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
}
